﻿using Autofac;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Text;


namespace Sprout.Core
{
    /**
     * 经测试
     * 如果是AddScoped 模式，通过GetService 获取到的值全局唯一，为单例
     * 同等于AddSingleton 模式
     */
    public class ServiceLocator
    {
        public static ILifetimeScope AutofacContainer { get; set; }

        public static T GetService<T>()
        {
            
            return AutofacContainer.Resolve<T>();
        }

        public static bool IsRegistered<T>()
        {
            return AutofacContainer.IsRegistered<T>();
        }

        public static bool IsRegistered<T>(string key)
        {
            return AutofacContainer.IsRegisteredWithKey<T>(key);
        }

        public static bool IsRegistered(Type type)
        {
            return AutofacContainer.IsRegistered(type);
        }

        public static bool IsRegisteredWithKey(string key, Type type)
        {
            return AutofacContainer.IsRegisteredWithKey(key, type);
        }

        public static T GetService<T>(string key)
        {

            return AutofacContainer.ResolveKeyed<T>(key);
        }

        public static object GetService(Type type)
        {
            return AutofacContainer.Resolve(type);
        }

        public static object GetService(string key, Type type)
        {
            return AutofacContainer.ResolveKeyed(key, type);
        }

        /// <summary>
        /// 获取Option
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T GetOption<T>()
             where T : class, new()
        {
            return GetService<IOptions<T>>().Value;
        }
    }
}
